import 'dart:developer';

import 'package:FlutterDemo/common/commons.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

/// https://blog.csdn.net/CNAD666/article/details/107744163
class SampleFlutterBloc5 extends StatefulWidget {
  const SampleFlutterBloc5({Key? key}) : super(key: key);

  @override
  _SampleFlutterBloc5State createState() => _SampleFlutterBloc5State();
}

class _SampleFlutterBloc5State extends State<SampleFlutterBloc5> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "Sample BlocConsumer",
      home: Scaffold(
        appBar: AppBar(
          title: Text("Sample BlocConsumer"),
        ),
        body: BlocProvider(
          create: (context) => MyCounterBloc(),
          child: BlocConsumer<MyCounterBloc, int>(builder: (context, count) {
            return Container(
              child: Column(
                children: [
                  Padding(
                    padding: EdgeInsets.all(24),
                    child: Text(
                      "$count",
                      style: TextStyle(fontSize: 37),
                    ),
                  ),
                  buildCommonRaisedButton("+", 20.0, () {
                    context.read<MyCounterBloc>().add(MyCounterEvent.increment);
                  }),
                  buildCommonRaisedButton("-", 20.0, () {
                    context.read<MyCounterBloc>().add(MyCounterEvent.decrement);
                  })
                ],
              ),
            );
          }, listener: (context, state) {
            log("BlocConsumer onchange $state");
          }),
        ),
      ),
    );
  }
}

enum MyCounterEvent { increment, decrement }

class MyCounterBloc extends Bloc<MyCounterEvent, int> {
  MyCounterBloc() : super(0);

  @override
  Stream<int> mapEventToState(MyCounterEvent event) async* {
    switch (event) {
      case MyCounterEvent.increment:
        yield state + 1;
        break;
      case MyCounterEvent.decrement:
        yield state - 1;
        break;
    }
  }
}
